import java.util.PriorityQueue;

class MyTimertask implements Comparable<MyTimertask>{
    private Runnable runnable;
    private long time;

    public MyTimertask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }

    public long getTime() {
        return time;
    }
    public void run(){
        runnable.run();
    }
    @Override
    public int compareTo(MyTimertask o) {
        return (int) (this.time-o.time);
    }
}


class MyTimer{
    private Thread t=null;
    private PriorityQueue<MyTimertask> queue =new PriorityQueue<>();
    private Object locker=new Object();
    public void schedule(Runnable runnable,long delay){
        MyTimertask task=new MyTimertask(runnable,delay);
        queue.offer(task);
        locker.notify();
    }
    public MyTimer(){
        t=new Thread(()->{
            try {
                while (true){
                    synchronized (locker){
                        while (queue.isEmpty()){
                            //等待
                            try {
                                locker.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        MyTimertask curtask=queue.peek();
                        if (System.currentTimeMillis()>=curtask.getTime()){
                            queue.poll();
                            curtask.run();
                        }else {
                            locker.wait(curtask.getTime()-System.currentTimeMillis());
                        }
                    }
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }

        });
    }

}




public class Test {
}
